package timing.ukulele.persistence.handler;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Base64;

/**
 * 注意！！ 必须开启映射注解
 *
 * @TableName(autoResultMap = true)
 */
@Slf4j
public abstract class BaseEncryptDecryptHandler implements TypeHandler<String> {

    protected abstract String getKey();

    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if (!StringUtils.hasText(getKey()))
            throw new SQLException("没有配置密钥");
        if (StringUtils.hasText(parameter)) {
            try {
                SecretKeySpec keySpec = new SecretKeySpec(getKey().getBytes(), "AES");
                Cipher cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.ENCRYPT_MODE, keySpec);
                byte[] encryptedBytes = cipher.doFinal(parameter.getBytes());
                ps.setString(i, Base64.getEncoder().encodeToString(encryptedBytes));
            } catch (Exception e) {
                log.error("注意密钥长度，通常为16字节（128位）、24字节（192位）或32字节（256位）");
                throw new SQLException("Encryption failed", e);
            }
        }
    }

    @Override
    public String getResult(ResultSet rs, String columnName) throws SQLException {
        return decrypt(rs.getString(columnName));
    }

    @Override
    public String getResult(ResultSet rs, int columnIndex) throws SQLException {
        return decrypt(rs.getString(columnIndex));
    }

    @Override
    public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return decrypt(cs.getString(columnIndex));
    }

    private String decrypt(String encryptedText) throws SQLException {
        if (!StringUtils.hasText(getKey()))
            throw new SQLException("没有配置密钥");
        if(!StringUtils.hasText(encryptedText)) {
            return null;
        }
        try {
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
            SecretKeySpec keySpec = new SecretKeySpec(getKey().getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            log.error("注意密钥长度，通常为16字节（128位）、24字节（192位）或32字节（256位）");
            throw new SQLException("Decryption failed", e);
        }
    }
}
